<?php

namespace app\install\controller;

use app\install\controller\Base;

class Index extends Base
{

    // 页面
    public function index()
    {
        if (file_exists(RUNTIME_PATH . '/install.lock')) {
            exit('
<div class="alert alert-warning">您已经安装过，如需重新安装请修改<font color=red> runtime/install.lock 为 install.php </font>后再访问安装！</div>');
        }
        return view("/index");
    }
    // 操作
    public function import()
    {
        if (file_exists(RUNTIME_PATH . '/install.lock')) {
            exit('');
        }
        $host = input('host'); //数据库连接地址
        $username = input('username'); //数据库账号
        $password = input('userpass'); //数据库密码
        $dbname = input('name'); //数据库
        // 创建连接
        @$conn = mysqli_connect($host, $username, $password, $dbname);
        // 检测连接
        if (!$conn) {
            return json_encode(['code' => '-1', "msg" => "数据库连接失败"]);
        }
        $cof = [
            'hostname' => $host,
            'database' => $dbname,
            'username' => $username,
            'password' => $password,
        ];
        if (!setConfigAll("database", $cof)) {
            return json_encode(['code' => '-1', "msg" => "配置保存失败"]);
        }
        $msginfo = [];
        $sql = file_get_contents(ROOT_PATH . "data.sql");
        $sqlall = explode(";", $sql);
        $i = 0;
        foreach ($sqlall as $key) {
            if (@$conn->query($key) === TRUE) {
                // echo '<label>数据表' . $i . '创建成功</label>   ';
                $msginfo[$i] = true;
            } else {
                $msginfo[$i] = $conn->error;
                // return json_encode(['code' => '-1', "msg" => $conn->error]);
            }
            $i++;
        }
        $conn->close();
        if (rename(RUNTIME_PATH . 'install.php', RUNTIME_PATH . 'install.lock')) {
            return json_encode(['code' => "0", "msg" => "安装完成，如果无法正常打开，请手动检查数据库是否导入成功", "data" => $msginfo]);
        } else {
            return json_encode(['code' => '-1', "msg" => "安装失败"]);
        }
    }
}
